package com.token;

import org.springframework.http.HttpStatus;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.logging.Logger;

/**
 * 过滤器 JWTFilter
 */
public class JWTFilter extends BasicHttpAuthenticationFilter {

    /**
     * 第二步
     * 是否能进下一步处理
     * @param request
     * @param response
     * @param mappedValue
     * @return  true可以访问action了，false则执行onAccessDenied
     */
    protected boolean isAccessAllowed(ServletRequest request,ServletResponse response,Object mappedValue){
        try{
            //得到客户端传过来的令牌
            String token=((HttpServletRequest)request).getHeader("token");
            System.out.println("JWTFilter.isAccessAllowed-token:="+token);

            //封装
            JWTToken jwtToken=new JWTToken(token);
            System.out.println("JWTFilter.isAccessAllowed-jwtToken:="+jwtToken);
            //登录：实际是调用LoginRealm里面doGetAuthenticationInfo

            getSubject(request,response).login(jwtToken);
            //判断是否有权限
            String url=((HttpServletRequest)request).getRequestURI();
            System.out.println("JWTFilter.isAccessAllowed-url:="+url);

            getSubject(request,response).checkPermission(url);

            return true;
        }catch (Exception e){
            return false;
        }
    }


    protected boolean onAccessDenied(ServletRequest request,ServletResponse response){
        HttpServletResponse r=(HttpServletResponse) response;
        System.out.println("JWTFilter.onAccessDenied-r:="+r);

        r.setStatus(401);
        return false;
    }

    /**
     * 用于跨域   第一步
     * @param request
     * @param response
     * @return true 可以进下一步isAccessAllowed，如果false则被拦截不能通过
     * @throws Exception
     */

    @Override
    protected boolean  preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.addHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.addHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE");
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "token");

        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())){
            httpServletResponse.setStatus(HttpStatus.OK.value());
            System.out.println("JWTFilter.proHrandle.===来了");
            return false;
        }

        //更新令牌并发送给客户端   这五个类都不要注入bean
        String token=((HttpServletRequest)request).getHeader("token");
        System.out.println("JWTFilter.proHrandle.token==="+token);
        Logger.getLogger("SHIRO").info(token);
        String newToken=JwtUtil.updateToken(token);
        System.out.println("JWTFilter.proHrandle.newToken==="+newToken);
        Logger.getLogger("SHIRO").info(newToken);

        if (newToken.length()>0){
            httpServletResponse.addHeader("token",newToken);
        }
        return super.preHandle(request,response);

    }

}
